package com.rrqs.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.List;
import java.util.Map;

public class JsonUtils {

	public static <T> T json2Class(String json, Class<T> clazz) {
		return JSON.parseObject(json, clazz);  
	}

	public static <T> List<T> json2List(String json, Class<T> clazz) {
		return  JSON.parseArray(json, clazz);
	}
	
	public static <T> List<T> jsonArr2List(JSONArray arr, Class<T> clazz) {
		return  JSON.parseArray(JSON.toJSONString(arr), clazz);
	}
	
	public static <T> String x2json(Object object) {
		return  JSON.toJSONString(object);  
	}
	
	public static JSONObject string2json(String str) {
		return  JSON.parseObject(str);
	}

	@SuppressWarnings("unchecked")
	public static Map<String, Object> json2Map(String json) {
		return (Map<String, Object>)JSON.parse(json);
	}



	public static String formatJson(String jsonStr) {
		if (null == jsonStr || "".equals(jsonStr))
			return "";
		StringBuilder sb = new StringBuilder();
		char last = '\0';
		char current = '\0';
		int indent = 0;
		boolean isInQuotationMarks = false;
		for (int i = 0; i < jsonStr.length(); i++) {
			last = current;
			current = jsonStr.charAt(i);
			switch (current) {
				case '"':
					if (last != '\\'){
						isInQuotationMarks = !isInQuotationMarks;
					}
					sb.append(current);
					break;
				case '{':
				case '[':
					sb.append(current);
					if (!isInQuotationMarks) {
						sb.append('\n');
						indent++;
						addIndentBlank(sb, indent);
					}
					break;
				case '}':
				case ']':
					if (!isInQuotationMarks) {
						sb.append('\n');
						indent--;
						addIndentBlank(sb, indent);
					}
					sb.append(current);
					break;
				case ',':
					sb.append(current);
					if (last != '\\' && !isInQuotationMarks) {
						sb.append('\n');
						addIndentBlank(sb, indent);
					}
					break;
				default:
					sb.append(current);
			}
		}

		return sb.toString();
	}

	private static void addIndentBlank(StringBuilder sb, int indent) {
		for (int i = 0; i < indent; i++) {
			sb.append('\t');
		}
	}
}
